//
//  WuyouTangAddGoodsVC.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/28.
//  Copyright © 2019 cat. All rights reserved.
//

#import "WuyouTangAddGoodsVC.h"
#import <Qiniu/QiniuSDK.h>
#import "UIView+LBExtension.h"
#import "YBStorageObj.h"
@interface WuyouTangAddGoodsVC ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>{
    UITextView *linkT;
    UITextView *nameT;
    UITextView *yuanjiaT;
    UITextView *xianjiaT;
    UITextView *contentT;
    UIButton *shopImgBtn;
    UIImage *selectImg;
    UIButton *addBtn;
    NSMutableArray *btnArray;
    UIView *moveLineView;
    UIScrollView *backScroll;
    
    UIScrollView *wxScroll;
    UIButton *wxAddBtn;
    UITextView *idT;
    UITextView *nameT2;
    UITextView *yuanjiaT2;
    UITextView *xianjiaT2;
    UITextView *contentT2;
    UIImageView *goodsThumbImgV;
    NSString *addType;
    NSDictionary *wxGoodsDic;
}

@end

@implementation WuyouTangAddGoodsVC

- (void)ChangeBtnBackground{
    if (linkT.text.length > 0 && nameT.text.length > 0 && xianjiaT.text.length > 0  && contentT.text.length > 0 && (selectImg||![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"thumb"])])) {
        addBtn.alpha = 1;
        addBtn.userInteractionEnabled = YES;
    }else{
        addBtn.alpha = 0.5;
        addBtn.userInteractionEnabled = NO;
    }
}
- (void)topBtnClick:(UIButton *)sender{
    if (sender.selected) {
        return;
    }
    [UIView animateWithDuration:0.3 animations:^{
        moveLineView.centerX = sender.centerX;
    }];
    for (UIButton *btn in btnArray) {
        if (sender == btn) {
            btn.selected = YES;
        }else{
            btn.selected = NO;
        }
    }
    if (sender.tag == 1000) {
        addType = @"0";
        backScroll.hidden = NO;
        wxScroll.hidden = YES;
    }else{
        addType = @"1";
        backScroll.hidden = YES;
        wxScroll.hidden = NO;
    }
}
- (void)creatNaviIteam{
    btnArray = [NSMutableArray array];
    NSArray *array = @[YZMsg(@"添加商品")];//,@"商城小程序"
    for (int i = 0; i < array.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.frame = CGRectMake(_window_width/2-130/2 + i *130, 24+statusbarHeight, 130, 40);
        [btn setTitle:array[i] forState:0];
        [btn setTitleColor:RGB_COLOR(@"#777777", 1) forState:0];
        [btn setTitleColor:RGB_COLOR(@"#ffffff", 1) forState:UIControlStateSelected];
        btn.titleLabel.font = SYS_Font(16);
        [btn addTarget:self action:@selector(topBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = 1000 + i;
        [self.naviView addSubview:btn];
        [btnArray addObject:btn];
        if (i == 0) {
            btn.selected = YES;
            moveLineView = [[UIView alloc]initWithFrame:CGRectMake(btn.centerX-7.5, btn.bottom-5, 15, 3)];
            moveLineView.backgroundColor = [UIColor clearColor];
            moveLineView.layer.cornerRadius =1;
            moveLineView.layer.masksToBounds = YES;
            [self.naviView addSubview:moveLineView];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selfTapClick)];
    [self.view addGestureRecognizer:tap];
    addType = @"0";
    [self creatNaviIteam];
    [self creatUI];
    [self creatWXScroll];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeBtnBackground) name:UITextViewTextDidChangeNotification object:nil];
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewEditChanged:) name:UITextViewTextDidChangeNotification object:nil];
    if (_goodsInfo) {
        NSString *typestr = minstr([_goodsInfo valueForKey:@"type"]);
        if ([typestr isEqual:@"1"]) {
            UIButton *selBtn = (UIButton *)[self.naviView viewWithTag:1001];
            [self topBtnClick:selBtn];
            idT.text = @"239";//minstr([_goodsInfo valueForKey:@"id"]);
            [self getGoodsMsgBtnClick];
        }
    }
    [self ChangeBtnBackground];
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)creatUI{
    backScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight)];
    [self.view addSubview:backScroll];
    NSArray *array = @[YZMsg(@"*商品链接(可粘贴淘宝店铺商品链接)"),YZMsg(@"*商品名称(最多可输入20个字)"),YZMsg(@"原价(元)"),YZMsg(@"*现价(元)"),YZMsg(@"*商品简介(最多可输入50个字)"),YZMsg(@"*商品图片")];
    CGFloat yyyy = 0.0;
    for (int i = 0; i < array.count; i ++) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, yyyy, _window_width, 30)];
        [backScroll addSubview:view];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, view.width-20, view.height)];
        label.textColor = RGB_COLOR(@"#969696", 1);
        label.font = [UIFont systemFontOfSize:12];
        [view addSubview:label];
        label.attributedText = [self setAttStr:array[i]];
        UIView *textView = [[UIView alloc]initWithFrame:CGRectMake(0, view.bottom, _window_width, 40)];
        textView.backgroundColor = CellRow_Cor;//RGB_COLOR(@"#FAFAFA", 1);
        if (i == 4) {
            textView.height = 70;
        }
        if (i == 5) {
            textView.height = 120;
        }
        [backScroll addSubview:textView];
        
        if (i != 5) {
            UITextView *textT = [[UITextView alloc]initWithFrame:CGRectMake(20, 0, textView.width-40, 40)];
            textT.font = [UIFont systemFontOfSize:13];
            textT.textColor = RGB_COLOR(@"#969696", 1);
            textT.backgroundColor = [UIColor clearColor];
            textT.delegate = self;
            [textView addSubview:textT];
            switch (i) {
                case 0:
                    
                    linkT = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"href"])]) {
                        linkT.text = minstr([_goodsInfo valueForKey:@"href"]);
                    }
                    break;
                case 1:
                    nameT = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"name"])]) {
                        nameT.text = minstr([_goodsInfo valueForKey:@"name"]);
                    }
                    
                    break;
                case 2:
                    yuanjiaT = textT;
                    if ([_goodsInfo valueForKey:@"old_price"]) {
                        yuanjiaT.text = minstr([_goodsInfo valueForKey:@"old_price"]);
                    }
                    
                    break;
                case 3:
                    xianjiaT = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"price"])]) {
                        xianjiaT.text = minstr([_goodsInfo valueForKey:@"price"]);
                    }
                    
                    break;
                case 4:
                    contentT = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"des"])]) {
                        contentT.text = minstr([_goodsInfo valueForKey:@"des"]);
                    }
                    
                    break;
                    
                default:
                    break;
            }
        }else{
            textView.backgroundColor = [UIColor clearColor];
            shopImgBtn = [UIButton buttonWithType:0];
            shopImgBtn.frame = CGRectMake(15, 0, 90, 120);
            [shopImgBtn setImage:[UIImage imageNamed:@"video_shop_add"] forState:0];
            //[shopImgBtn setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0.03]];
            [shopImgBtn addTarget:self action:@selector(shopImgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            shopImgBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
            [textView addSubview:shopImgBtn];
            if ([_goodsInfo allKeys].count>0) {
                if ([[_goodsInfo valueForKey:@"thumb"] isKindOfClass:[UIImage class]]) {
                    selectImg = [_goodsInfo valueForKey:@"thumb"];
                    [shopImgBtn setImage:selectImg forState:0];
                }else {
                    [shopImgBtn sd_setImageWithURL:[NSURL URLWithString:minstr([_goodsInfo valueForKey:@"thumb"])] forState:0];
                }
            }
            
        }
        
        yyyy = textView.bottom;
        
    }
    addBtn = [UIButton buttonWithType:0];
    addBtn.frame = CGRectMake(15, yyyy + 20, _window_width-30, 40);
    [addBtn setBackgroundColor:Pink_Cor];
    addBtn.alpha = 0.5;
    addBtn.userInteractionEnabled = NO;
    [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setTitle:YZMsg(@"确认商品信息") forState:0];
    addBtn.layer.cornerRadius = 5;
    addBtn.layer.masksToBounds = YES;
    addBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [backScroll addSubview:addBtn];
    backScroll.contentSize = CGSizeMake(0, addBtn.bottom);
}
-(void)textViewEditChanged:(NSNotification *)noti {
    UITextView *changeTextView = (UITextView *)noti.object;
    NSString *toBeString = changeTextView.text;
    NSString *lang = [[[UITextInputMode activeInputModes]firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [changeTextView markedTextRange];//获取高亮部分
        UITextPosition *position = [changeTextView positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (changeTextView == nameT) {
                if (toBeString.length > 20) {
                    changeTextView.text = [toBeString substringToIndex:20];
                    [MBProgressHUD showPop:YZMsg(@"最多可输入20个字")];
                }
            }
            if (changeTextView == contentT) {
                if (toBeString.length > 50) {
                    changeTextView.text = [toBeString substringToIndex:50];
                    [MBProgressHUD showPop:YZMsg(@"最多可输入50个字")];
                }
            }
        }else{
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else{
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (changeTextView == nameT) {
            if (toBeString.length > 20) {
                changeTextView.text = [toBeString substringToIndex:20];
                [MBProgressHUD showPop:YZMsg(@"最多可输入20个字")];
            }
        }
        if (changeTextView == contentT) {
            if (toBeString.length > 50) {
                changeTextView.text = [toBeString substringToIndex:50];
                [MBProgressHUD showPop:YZMsg(@"最多可输入50个字")];
            }
        }
    }
}
//- (void)textViewDidChange:(UITextView *)textView; {
//    if (textView == nameT) {
//        if (textView.text.length > 20) {
//            textView.text = [textView.text substringToIndex:20];
//            [MBProgressHUD showPop:YZMsg(@"最多可输入20个字")];
//        }
//    }
//    if (textView == contentT) {
//        if (textView.text.length > 50) {
//            textView.text = [textView.text substringToIndex:50];
//            [MBProgressHUD showPop:YZMsg(@"最多可输入50个字")];
//        }
//    }
//}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;{
    if (textView == xianjiaT || textView == yuanjiaT) {
        //新输入的
        if (text.length == 0) {
            return YES;
        }
        NSString *checkStr = [textView.text stringByReplacingCharactersInRange:range withString:text];
        //正则表达式（只支持两位小数）
        NSString *regex = @"^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$";;
        //判断新的文本内容是否符合要求
        return [self isValid:checkStr withRegex:regex];
    }
    return YES;
}
- (BOOL) isValid:(NSString*)checkStr withRegex:(NSString*)regex {
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicte evaluateWithObject:checkStr];
}

- (void)creatWXScroll{
    
    wxScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-64-statusbarHeight)];
    wxScroll.hidden = YES;
    [self.view addSubview:wxScroll];
    NSArray *array = @[YZMsg(@"商品ID（输入小程序中商品对应ID，将自动获取商品信息）"),YZMsg(@"商品名称"),YZMsg(@"原价"),YZMsg(@"现价"),YZMsg(@"商品简介"),YZMsg(@"商品图片")];
    CGFloat yyyy = 0.0;
    for (int i = 0; i < array.count; i ++) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, yyyy, _window_width, 30)];
        [wxScroll addSubview:view];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, view.width-20, view.height)];
        label.textColor = RGB_COLOR(@"#969696", 1);
        label.font = [UIFont systemFontOfSize:12];
        [view addSubview:label];
        UIView *textView = [[UIView alloc]initWithFrame:CGRectMake(0, view.bottom, _window_width, 40)];
        if (i == 0) {
            textView.height = 60;
        }
        if (i == 4) {
            textView.height = 80;
        }
        if (i == 5) {
            textView.height = 90;
        }
        [wxScroll addSubview:textView];
        if (i == 0) {
            //label.attributedText = [self setWXAttStr:array[i]];
            label.text = array[i];
            textView.userInteractionEnabled = YES;
            textView.backgroundColor = CellRow_Cor;
        }else{
            label.text = array[i];
            textView.userInteractionEnabled = NO;
            textView.backgroundColor = CellRow_Cor;//RGB_COLOR(@"#FAFAFA", 1);
            
        }
        
        if (i != 5) {
            UITextView *textT = [[UITextView alloc]initWithFrame:CGRectMake(20, 0, textView.width-40, 40)];
            textT.font = [UIFont systemFontOfSize:13];
            textT.textColor = RGB_COLOR(@"#969696", 1);
            textT.backgroundColor = [UIColor clearColor];
            textT.delegate = self;
            [textView addSubview:textT];
            if (i == 0) {
                textT.top = 5;
                textT.backgroundColor = RGB_COLOR(@"#ffffff", 0.03);
                textT.width = textView.width-150;
                //                textT.layer.borderWidth = 1;
                //                textT.layer.borderColor = RGB_COLOR(@"#eeeeee", 1).CGColor;
                UIButton *getGoodsMsgBtn = [UIButton buttonWithType:0];
                getGoodsMsgBtn.frame = CGRectMake(textT.right + 10, textT.top+5, 100, 30);
                [getGoodsMsgBtn setBackgroundColor:Pink_Cor];
                [getGoodsMsgBtn addTarget:self action:@selector(getGoodsMsgBtnClick) forControlEvents:UIControlEventTouchUpInside];
                [getGoodsMsgBtn setTitle:YZMsg(@"获取商品信息") forState:0];
                getGoodsMsgBtn.layer.cornerRadius = 5;
                getGoodsMsgBtn.layer.masksToBounds = YES;
                getGoodsMsgBtn.titleLabel.font = [UIFont systemFontOfSize:12];
                [textView addSubview:getGoodsMsgBtn];
                
            }
            switch (i) {
                case 0:
                    
                    idT = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"href"])]) {
                        linkT.text = minstr([_goodsInfo valueForKey:@"href"]);
                    }
                    break;
                case 1:
                    nameT2 = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"name"])]) {
                        nameT.text = minstr([_goodsInfo valueForKey:@"name"]);
                    }
                    
                    break;
                case 2:
                    yuanjiaT2 = textT;
                    if ([_goodsInfo valueForKey:@"old_price"] && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"old_price"])]) {
                        yuanjiaT.text = minstr([_goodsInfo valueForKey:@"old_price"]);
                    }
                    
                    break;
                case 3:
                    xianjiaT2 = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"price"])]) {
                        xianjiaT.text = minstr([_goodsInfo valueForKey:@"price"]);
                    }
                    
                    break;
                case 4:
                    contentT2 = textT;
                    if (_goodsInfo && ![PublicObj checkNull:minstr([_goodsInfo valueForKey:@"des"])]) {
                        contentT.text = minstr([_goodsInfo valueForKey:@"des"]);
                    }
                    
                    break;
                    
                default:
                    break;
            }
        }else{
            textView.backgroundColor = [UIColor clearColor];
            
            goodsThumbImgV = [[UIImageView alloc]initWithFrame:CGRectMake(15, 0, 90, 90)];
            goodsThumbImgV.backgroundColor = CellRow_Cor;//RGB_COLOR(@"#fafafa", 1);
            goodsThumbImgV.contentMode = UIViewContentModeScaleAspectFill;
            goodsThumbImgV.clipsToBounds = YES;
            [textView addSubview:goodsThumbImgV];
        }
        
        yyyy = textView.bottom;
        
    }
    wxAddBtn = [UIButton buttonWithType:0];
    wxAddBtn.frame = CGRectMake(15, yyyy + 20, _window_width-30, 40);
    [wxAddBtn setBackgroundColor:Pink_Cor];
    wxAddBtn.alpha = 0.5;
    wxAddBtn.userInteractionEnabled = NO;
    [wxAddBtn addTarget:self action:@selector(wxAddBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [wxAddBtn setTitle:YZMsg(@"确认商品信息") forState:0];
    wxAddBtn.layer.cornerRadius = 5;
    wxAddBtn.layer.masksToBounds = YES;
    wxAddBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [wxScroll addSubview:wxAddBtn];
    wxScroll.contentSize = CGSizeMake(0, wxAddBtn.bottom);
    
    
    
}
- (NSMutableAttributedString *)setAttStr:(NSString *)str{
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:str];
    if ([str hasPrefix:@"*"]) {
        [attStr addAttribute:NSForegroundColorAttributeName
                       value:[UIColor redColor]
                       range:NSMakeRange(0, 1)];
    }
    return attStr;
}
- (NSMutableAttributedString *)setWXAttStr:(NSString *)str{
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:str];
    NSRange range = [str rangeOfString:@"（"];
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:RGB_COLOR(@"#323232", 1)
                   range:NSMakeRange(0, range.location)];
    [attStr addAttribute:NSFontAttributeName
                   value:SYS_Font(10)
                   range:NSMakeRange(range.location, str.length - range.location)];
    
    return attStr;
}

- (void)shopImgBtnClick:(UIButton *)sender{
    
    [self.view endEditing:YES];
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"相机") complete:^{
        [weakSelf takePhoto];
    }];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"相册") complete:^{
        [weakSelf selectPhotos];
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
    
}
- (void)takePhoto{
    // 区分拍照-相册
    UIImagePickerController *imagePickerController = [UIImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePickerController.allowsEditing = NO;
    imagePickerController.showsCameraControls = YES;
    imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
-(void)selectPhotos {
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.showSelectBtn = YES;
    imagePC.allowCrop = NO;
    imagePC.allowPickingOriginalPhoto = NO;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.allowTakePicture = YES;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.allowPickingMultipleVideo = NO;
    imagePC.modalPresentationStyle = 0;
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    selectImg = photos[0];
    [shopImgBtn setImage:selectImg forState:UIControlStateNormal];
    [self ChangeBtnBackground];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        UIImageOrientation imageOrientation = image.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }
        
        selectImg = image;
        [shopImgBtn setImage:image forState:UIControlStateNormal];
        [self ChangeBtnBackground];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([UIDevice currentDevice].systemVersion.floatValue < 11) {
        return;
    }
    if ([viewController isKindOfClass:NSClassFromString(@"PUPhotoPickerHostViewController")]) {
        [viewController.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.frame.size.width < 42) {
                [viewController.view sendSubviewToBack:obj];
                *stop = YES;
            }
        }];
    }
}

- (void)addBtnClick:(UIButton *)sender{
    if ([PublicObj checkNull:linkT.text]) {
        [MBProgressHUD showError:YZMsg(@"请输入商品链接")];
        return;
    }
    
    if ([PublicObj checkNull:nameT.text]) {
        [MBProgressHUD showError:YZMsg(@"请输入商品名称")];
        return;
    }
    if ([PublicObj checkNull:xianjiaT.text]) {
        [MBProgressHUD showError:YZMsg(@"请输入商品价格")];
        return;
    }
    if ([PublicObj checkNull:contentT.text]) {
        [MBProgressHUD showError:YZMsg(@"请输入商品简介")];
        return;
    }
    if (contentT.text.length > 50) {
        [MBProgressHUD showError:YZMsg(@"商品简介最多50字")];
        return;
    }
    
    if (!selectImg && [PublicObj checkNull:minstr([_goodsInfo valueForKey:@"thumb"])]) {
        [MBProgressHUD showError:YZMsg(@"请上传商品封面")];
        return;
    }
    if (selectImg) {
        YBWeakSelf;
        [[YBStorageObj storageManeger]getCOSType:^(int code) {
            if (code == 0) {
                [weakSelf uploadImg];
            }
        }];
    }else {
        [self uploadFinish:minstr([_goodsInfo valueForKey:@"thumb"])];
    }
}

-(void)uploadImg {
    [MBProgressHUD showMessage:@""];
    NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_goods.png"];
    YBWeakSelf;
    [[YBStorageObj storageManeger]yb_storageImg:selectImg andName:imageName progress:^(CGFloat percent) {
        
    } complete:^(int code, NSString *key) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
        });
        if (code == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf uploadFinish:key];
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD showPop:YZMsg(@"添加失败")];
            });
        }
    }];
    
}
-(void)uploadFinish:(NSString *)finishPath {
  
    /*
    NSDictionary *originDic = @{
        @"id":@"0",
        @"href":linkT.text,
        @"name":nameT.text,
        @"price":xianjiaT.text,
        @"old_price":yuanjiaT.text,
        @"des":contentT.text,
        @"thumb":finishPath
    };
    NSMutableDictionary *o_dic = @{@"type":@"0"}.mutableCopy;
    [o_dic addEntriesFromDictionary:originDic];
    NSLog(@"<<><><><>:%@",o_dic);
    
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:o_dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *goodsinfo = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"====:%@==json%@",o_dic,goodsinfo);
    if (self.addGoodsEvent) {
        self.addGoodsEvent(o_dic, goodsinfo);
    }
    [self.navigationController popViewControllerAnimated:YES];
    */
    
    NSDictionary *postDic = @{@"name":nameT.text,
                              @"href":linkT.text,
                              @"thumb":finishPath,
                              @"old_price":yuanjiaT.text,
                              @"price":xianjiaT.text,
                              @"des":contentT.text,
                              @"type":@"0",
    };
    NSString *postUrl = @"Shop.setGoods";
    if (_isUpdateGoods) {
        postDic = @{@"name":nameT.text,
                    @"href":linkT.text,
                    @"thumb":finishPath,
                    @"old_price":yuanjiaT.text,
                    @"price":xianjiaT.text,
                    @"des":contentT.text,
                    @"type":@"0",
                    @"goodsid":minstr([_goodsInfo valueForKey:@"id"]),
        };
        postUrl = @"Shop.updateGoods";
    }
    YBWeakSelf;
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:postUrl Dic:postDic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:msg];
        if (code == 0) {
            if (weakSelf.addRefreshEvnet) {
                weakSelf.addRefreshEvnet();
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}

- (void)selfTapClick{
    [self.view endEditing:YES];
}

- (void)getGoodsMsgBtnClick{
    if ([PublicObj checkNull:idT.text]) {
        [MBProgressHUD showError:YZMsg(@"请输入商品ID")];
        return;
    }
    [idT resignFirstResponder];
    [MBProgressHUD showMessage:@""];
    [WYNetworking postWithUrl:@"Shop.GetApplets" Dic:@{@"id":idT.text} Suc:^(int code, id info, NSString *msg) {
        
        [MBProgressHUD hideHUD];
        
        if (code == 0) {
            wxGoodsDic = info;
            nameT2.text = minstr([wxGoodsDic valueForKey:@"name"]);
            yuanjiaT2.text = minstr([wxGoodsDic valueForKey:@"old_price"]);
            xianjiaT2.text = minstr([wxGoodsDic valueForKey:@"price"]);
            contentT2.text = minstr([wxGoodsDic valueForKey:@"des"]);
            [goodsThumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([wxGoodsDic valueForKey:@"thumb"])]];
            wxAddBtn.alpha = 1;
            wxAddBtn.userInteractionEnabled = YES;
            
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}
- (void)wxAddBtnClick:(UIButton *)sender{
    /*
    NSMutableDictionary *dic = @{@"type":@"1"}.mutableCopy;
    [dic addEntriesFromDictionary:wxGoodsDic];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *goodsinfo = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"====:%@==json%@",dic,goodsinfo);
    if (self.addGoodsEvent) {
        self.addGoodsEvent(dic, goodsinfo);
    }
    [self.navigationController popViewControllerAnimated:YES];
    */
}

#pragma mark -- 获取键盘高度
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    if (contentT.isFirstResponder) {
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        CGFloat height = keyboardRect.origin.y;
        CGFloat heightw = keyboardRect.size.height;
        int newHeight = _window_height - height -44;
        [UIView animateWithDuration:0.3 animations:^{
            [backScroll setContentOffset:CGPointMake(0, heightw)];
        }];
    }
    //获取键盘的高度
}
- (void)keyboardWillHide:(NSNotification *)aNotification {
    
    
    [UIView animateWithDuration:0.1 animations:^{
        [UIView animateWithDuration:0.3 animations:^{
            [backScroll setContentOffset:CGPointMake(0, 0)];
        }];
    }];
}


@end
